package com.xoa.util.sendmsg;

import com.xoa.util.common.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.core.convert.converter.ConverterFactory;


import java.util.*;


/**
 * @author B-wy:
 * @version 创建时间：2017年6月8日 上午10:25:06 类说明 emc-发送工具类
 */
public class MessageUtil {

	public static Map channelCodeToId;

	public static Map channelCodeToName;


	/**
	 * @param title
	 *            标题
	 * @param content
	 *            内容
	 * @param channelCode
	 *            渠道编码
	 * @param netIds
	 *            内部人员IDS
	 * @param outAddresses
	 *            外部人员接收帐号
	 * @param isCron
	 *            是否定时 1=定时, 0=不定时
	 * @param sendTime
	 *            发送时间 定时时必填(yyyy-MM-dd HH:mm:ss)
	 *@param serviceUrl
	 *            url地址
	 *@param accountID
	 *            接入端帐号
	 *@param accountKey
	 *            接入端密钥
	 * @return
	 */
	public static String sendmsg(String title,
								 String content,
								 String channelCode,
								 List netIds,
								 List outAddresses,
								 int isCron,
								 String sendTime,
								 String serviceUrl,
								 String accountID,
								 String accountKey
	) {
		if(StringUtils.checkNull(serviceUrl) && StringUtils.checkNull(accountID) && StringUtils.checkNull(accountKey)){
			return "-1";
		}
		if(channelCodeToId == null || channelCodeToId.get(channelCode) == null ){
			initChannelInfo(serviceUrl,accountID,accountKey);
		}

		Map result = new HashMap();
		String channelId = channelCodeToId.get(channelCode).toString();
		if(channelId == null){
			result.put("errcode", "40014");
			result.put("msg", "接入端没有此渠道的发送权限");
			return result.toString();
		}
		JSONObject dataJson = new JSONObject();
		// 手机号填入=ydxy-mobile, 邮件填入email
		dataJson.put("channels", channelCode);
		dataJson.put("channelIds", channelId);
		dataJson.put("title", title);
		dataJson.put("content", content);
		dataJson.put("intReceiver", netIds);

		JSONObject extReceivers = new JSONObject();
		extReceivers.put(channelCode, outAddresses);
		// 外部联系人,此处填入对应的渠道接收信息
		dataJson.put("extReceiver", extReceivers);
		dataJson.put("isCron", "" + isCron);
		if (isCron==1){
			dataJson.put("sendtime",sendTime);
		}
		HttpPost httpPost = new HttpPost(serviceUrl + "/restful/sendmsg");
		try {
			CloseableHttpClient client = HttpClients.createDefault();
			List params = new ArrayList();
			params.add(new BasicNameValuePair("accountID", accountID));
			params.add(new BasicNameValuePair("accountKey", accountKey));
			params.add(new BasicNameValuePair("msgJson", dataJson.toString()));

			HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8");
			httpPost.setEntity(httpEntity);
			CloseableHttpResponse response = client.execute(httpPost);
			return EntityUtils.toString(response.getEntity());
		} catch(Exception e){
			e.printStackTrace();
		}finally {
			httpPost.releaseConnection();
		}
		return null;
	}

	/**
	 * 刷新接入端可用渠道信息`0
	 */
	public static void initChannelInfo(String serviceUrl,String accountID,String accountKey) {
		if(channelCodeToId == null){
			channelCodeToId = new HashMap();
		}
		if(channelCodeToName == null){
			channelCodeToName = new HashMap();
		}
		String url = serviceUrl + "/restful/get_channels";
		Map data = new HashMap();
		data.put("accountID", accountID);
		data.put("accountKey", accountKey);
		HttpClientUtils client = new HttpClientUtils();
		JSONObject obj = client.httpGet(url, data);
		// 是否成功
		if (obj.getInt("errcode") == 0) {
			// 成功
			JSONObject res = obj.getJSONObject("data");
			// 获取手机渠道信息
			Set keys = res.keySet();
			Iterator tempKeys = keys.iterator();

			while(tempKeys.hasNext()) {
				String key = tempKeys.next().toString();
				JSONArray tempArray = res.getJSONArray(key);
				for (int i = 0; i < tempArray.size(); i++) {
					JSONObject temp = tempArray.getJSONObject(i);
					// 判断通道是否可用
					if (temp.getString("status").equals("0")) {
						channelCodeToId.put(key, temp.getString("id"));
						channelCodeToName.put(key, temp.getString("channelName"));
						break;
					}
				}
			}
		}
	}

	//测试
	/*public static void main(String[] args) {
		List outAddresses = new ArrayList();
		outAddresses.add("13729034581");
		//String result = sendmsg("OA待办", "会议内容如下: 1111.", "ydxy-mobile", new ArrayList(), outAddresses, 0, null);
		//System.out.println(result);
	}*/
}
